package com.tm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tm.mapper.UserTanhuaMapper;
import com.tm.service.UserTanhuaService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tm.pojo.*;
import tm.pojo.dto.AllLoveQuestionAndAnswerDTO;
import tm.pojo.dto.HomePageDto;
import tm.pojo.dto.LoveResultAnswer;
import tm.pojo.dto.TodayGirlDto;
import tm.result.Result;

import java.lang.reflect.Type;
import java.util.*;

/**
 * @author Rocky
 * @create 2022-09-26 11:48
 */
@Service
public class UserTanhuaServiceImpl implements UserTanhuaService {
    @Autowired
    private UserTanhuaMapper userTanhuaMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result thHomePage(HomePageDto homePageDto) {
        //最近来访
        List<TodayBeauty>list= userTanhuaMapper.queryVisitUser(homePageDto);
        for (int i = 0; i < list.size(); i++) {
            TodayBeauty todayBeauty = list.get(i);
        }
        return Result.SUCCESS(list);
    }

    @Override
    public Result getTodayGirl(TodayGirlDto todayGirlDto) {
        List<TodayBeauty>list=new ArrayList<>();
        UserPojo userPojo;
        try {
            //查询自己的个人信息
            userPojo= userTanhuaMapper.querySelfUserInfo(todayGirlDto.getUserId());
            //创建用来发起搜索请求的对象
            SearchRequest searchRequest = new SearchRequest("th-zkj");
            //创建一个搜索资源构造器
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //用来构建复合条件查询的构造器
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //should 应该(模糊查询) must必须(完全匹配) filter过滤(范围查询)

            //如果未传入年龄则查询相差两岁以内的
            if (todayGirlDto.getMinAge()!=null){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("userage").gte(todayGirlDto.getMinAge()));
            }
            if (todayGirlDto.getMaxAge()!=null){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("userage").lte(todayGirlDto.getMaxAge()));
            }
            if (todayGirlDto.getMinAge()==null && todayGirlDto.getMaxAge()==null){
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("userage").lte(userPojo.getUserage()+2).gte(userPojo.getUserage()-2));
            }
            //情感状态，如果不传入，则查询和自己相同的
            if (todayGirlDto.getEmotionalState()==null){
                boolQueryBuilder.should(QueryBuilders.matchQuery("emotionalstate",userPojo.getEmotionalstate()));
            }else {
                boolQueryBuilder.should(QueryBuilders.matchQuery("emotionalstate",todayGirlDto.getEmotionalState()));
            }
            //学历，如果不传入，则查询和自己相同的
            if (todayGirlDto.getEducationLevel()==null){
                boolQueryBuilder.should(QueryBuilders.matchQuery("educationlevel",userPojo.getEducationlevel()));
            }else {
                boolQueryBuilder.should(QueryBuilders.matchQuery("educationlevel",todayGirlDto.getEducationLevel()));
            }
            //
            //searchSourceBuilder的条件拼接查询
            searchSourceBuilder.query(boolQueryBuilder);
            //from起始下标=(当前页数-1)*每页条数        size每页条数
            //searchSourceBuilder.from(1).size(1);
            //所有条件都有，准备发起请求，构建、解析条件
            searchRequest.source(searchSourceBuilder);
            //得到的查询结果
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //根据响应结果获取所有数据
            SearchHits hits = response.getHits();
            TotalHits totalHits = hits.getTotalHits();
            long value = totalHits.value;   //总条数
            //value/每页条数 = 总页数;
            SearchHit[]hits1=hits.getHits();
            //hits1就是所有数据
            for (SearchHit documentFields : hits1) {
                Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
                Integer educationlevel =(Integer) sourceAsMap.get("educationlevel");
                Integer emotionalstate =(Integer) sourceAsMap.get("emotionalstate");
                String phonenumber =(String) sourceAsMap.get("phonenumber");
                Integer userage =(Integer) sourceAsMap.get("userage");
                String userimg =(String) sourceAsMap.get("userimg");
                String username =(String) sourceAsMap.get("username");
                Integer usersex =(Integer) sourceAsMap.get("usersex");
                TodayBeauty todayBeauty = new TodayBeauty();
                todayBeauty.setEducationLevel(educationlevel);
                todayBeauty.setEmotionalState(emotionalstate);
                todayBeauty.setPhoneNumber(phonenumber);
                todayBeauty.setUserAge(userage);
                todayBeauty.setUserimg(userimg);
                todayBeauty.setUserName(username);
                todayBeauty.setUserSex(usersex);
                if (Math.abs(userage-userPojo.getUserage())>10){
                    todayBeauty.setAgeLevel("灵魂伴侣");
                }else {
                    todayBeauty.setAgeLevel("年龄相仿");
                }
                Random random=new Random();
                int i = random.nextInt(95 - 85) + 85;
                todayBeauty.setHeartValue(i);
                list.add(todayBeauty);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.SUCCESS(list);
    }

    @Override
    public Result queryLoveTesting() {
        List<Integer>list= userTanhuaMapper.queryLoveTestingByid();
        //随机在list中取4个题
        List<Integer> list1 = randomNum(4, list.size());
        List<LoveQuestionPojo>loveQuestionPojos= userTanhuaMapper.queryQuestion(list1);
        return Result.SUCCESS(loveQuestionPojos);
    }

    @Override
    public Result queryLoveResult(LoveResultAnswer loveResultAnswer) {
        loveResultAnswer.setCreatetime(new Date().getTime()/1000);
        List<AllLoveQuestionAndAnswerDTO> allLoveQuestionAndAnswerList = loveResultAnswer.getAllLoveQuestionAndAnswerList();
        //循环集合，取出每个结果，判断是哪个就给那个选项+1
        allLoveQuestionAndAnswerList.forEach(a ->{
            switch (a.getAnswer()){
                case "a":
                    loveResultAnswer.setDeviationA(loveResultAnswer.getDeviationA()+1);
                    break;
                case "b":
                    loveResultAnswer.setDeviationB(loveResultAnswer.getDeviationB()+1);
                    break;
                case "c":
                    loveResultAnswer.setDeviationC(loveResultAnswer.getDeviationC()+1);
                    break;
                case "d":
                    loveResultAnswer.setDeviationD(loveResultAnswer.getDeviationD()+1);
                    break;
            }
        });
        //如果四项结果相同则为结果e
        if (loveResultAnswer.getDeviationA()==loveResultAnswer.getDeviationB() &&
                loveResultAnswer.getDeviationA()==loveResultAnswer.getDeviationC() &&
                loveResultAnswer.getDeviationA()==loveResultAnswer.getDeviationD()){
            loveResultAnswer.setDeviationE(22);
        }
        TanswerPojo build = new TanswerPojo.Builder().createtime(loveResultAnswer.getCreatetime()).questionOpstionPojo(JSONArray.toJSONString(allLoveQuestionAndAnswerList)).deviationA(loveResultAnswer.getDeviationA()).deviationB(loveResultAnswer.getDeviationB()).deviationC(loveResultAnswer.getDeviationC()).deviationD(loveResultAnswer.getDeviationD()).deviationE(loveResultAnswer.getDeviationE())
                .userId(loveResultAnswer.getUserId()).build();

        List <TanswerPojo>tanswerPojo= userTanhuaMapper.queryLoveAnswer();
        for (int i = 0; i < tanswerPojo.size(); i++) {
            TanswerPojo tanswerPojo1 = tanswerPojo.get(i);
            Integer userId = tanswerPojo1.getUserId();
            if (userId.equals(loveResultAnswer.getUserId())){
                return Result.SUCCESS("用户以填写过测试哦");
            }
        }
        userTanhuaMapper.addLoveResult(build);
        return Result.SUCCESS(build);
    }

    @Override
    public Result queryLoveTestingRecord(Integer userId) {
        TanswerPojo tanswerPojo= userTanhuaMapper.queryLoveTestingRecord(userId);
        if (tanswerPojo==null){
            return Result.ERROR();
        }
        String questionOpstionPojo = tanswerPojo.getQuestionOpstionPojo();
        List<AllLoveQuestionAndAnswerDTO> allLoveQuestionAndAnswerDTOS = JSONArray.parseArray(questionOpstionPojo, AllLoveQuestionAndAnswerDTO.class);
        LoveResultAnswer build = new LoveResultAnswer.Builder().allLoveQuestionAndAnswerList(allLoveQuestionAndAnswerDTOS).createtime(tanswerPojo.getCreatetime()).deviationA(tanswerPojo.getDeviationA())
                .deviationB(tanswerPojo.getDeviationB()).deviationC(tanswerPojo.getDeviationC()).deviationD(tanswerPojo.getDeviationE())
                .userId(tanswerPojo.getUserId()).build();
        return Result.SUCCESS(build);
    }

    @Override
    public Result soulMeet(Integer userId) {
         //* 1.根据用户id查到答题结果
        LoveResultAnswer loveResultAnswer = getLoveResultAnswer(userId);
        //先拿到ABCD的分值
        Integer deviationA = loveResultAnswer.getDeviationA();
        Integer deviationB = loveResultAnswer.getDeviationB();
        Integer deviationC = loveResultAnswer.getDeviationC();
        Integer deviationD = loveResultAnswer.getDeviationD();
        Integer deviationE = loveResultAnswer.getDeviationE();
        //* 2.查询会员状态
        Integer flag= userTanhuaMapper.queryUserSoulMemberInfo(userId);
        //* 3，查询所有该用户未查询过的数据
        Set members = redisTemplate.opsForSet().members("soul_user_" + userId);

        if (members.size()!=0 && members!=null){
            return Result.ERROR(999,"Redis中以有数据");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("deviationA",deviationA);
        map.put("deviationB",deviationB);
        map.put("deviationC",deviationC);
        map.put("deviationD",deviationD);
        map.put("deviationE",deviationE);
        map.put("flag",flag);
        map.put("members",members);
        //* 4.如果不是会员，择取redis查询是否本月已查询过
        List<UserPojo>list= userTanhuaMapper.querySoulMeetMember(map);
        List<Integer> list1 = new ArrayList<>();
        list.forEach(a ->{
            list1.add(a.getUserId());
        });
        //将查过得用户id添加到redis中去
        redisTemplate.opsForSet().add("soul_user_"+userId,list);

         //* 5.已经偶遇过得人，只能去历史记录查找

        return Result.SUCCESS(list);
    }

    @Override
    public UserPojo queryUser(Integer userId1) {
        return userTanhuaMapper.queryUser(userId1);
    }

    //查询语音表发送次数
    @Override
    public Result queryMp3Count(Integer userId) {
        Integer flg= userTanhuaMapper.queryMp3Count(userId);
        return Result.SUCCESS(flg);
    }

    @Override
    public Result addMemberMp3(MemberMp3 memberMp3) {
        userTanhuaMapper.addMemberMp3(memberMp3);
        return Result.SUCCESS();
    }

    @Override
    public Result queryMemberMp3(Integer userId) {
        Date date = new Date();
        LookMp3 lookMp3= userTanhuaMapper.queryLookMp3(userId);
        LookMp3 lookMp31 = new LookMp3();
        if (lookMp3!=null && lookMp3.getCreateTime().getDay()!=date.getDay()){
            lookMp31.setUserId(userId);
            lookMp31.setLookCount(0);
            userTanhuaMapper.updateLookMp3Bydate(lookMp31);
        }else {

        if (lookMp3!=null && lookMp3.getUserId()!=null){
            lookMp3.setUserId(userId);
            lookMp3.setLookCount(lookMp3.getLookCount()+1);
            userTanhuaMapper.updateLookMp3(lookMp3);
        }else {
            lookMp31.setUserId(userId);
            lookMp31.setLookCount(lookMp31.getLookCount());
            userTanhuaMapper.addLookMp3(lookMp31);
        }
          }
       //查询当前用户查询次数
        LookMp3 lookMp30= userTanhuaMapper.queryLookMp3Count(userId);
        Integer lookCount = lookMp30.getLookCount();
        if (lookCount>=10){
            return Result.ERROR(998,"今日查看已达上限");
        }
        List<MemberMp3>list=userTanhuaMapper.queryMp3();
        int random=(int)(Math.random()*10+1);
        List<MemberMp3>memberMp3s= userTanhuaMapper.queryMemberMp3(random);
        for (int i = 0; i < memberMp3s.size(); i++) {
            MemberMp3 memberMp3 = memberMp3s.get(i);
            Integer userId1 = memberMp3.getUserId();
            if (!userId1.equals(userId)){
                return Result.SUCCESS(memberMp3s);
            }
        }
        return Result.SUCCESS("未查询到，稍后再试");
    }

    @Override
    public Result queryMemberByLookMp3User() {

        return null;
    }


    //根据用户id查询用户的历史记录
    public LoveResultAnswer getLoveResultAnswer(Integer userId){
        TanswerPojo tanswerPojo= userTanhuaMapper.queryLoveTestingRecord(userId);
        String questionOpstionPojo = tanswerPojo.getQuestionOpstionPojo();
        List<AllLoveQuestionAndAnswerDTO> allLoveQuestionAndAnswerDTOS = JSONArray.parseArray(questionOpstionPojo, AllLoveQuestionAndAnswerDTO.class);
        LoveResultAnswer build = new LoveResultAnswer.Builder().allLoveQuestionAndAnswerList(allLoveQuestionAndAnswerDTOS).createtime(tanswerPojo.getCreatetime()).deviationA(tanswerPojo.getDeviationA())
                .deviationB(tanswerPojo.getDeviationB()).deviationC(tanswerPojo.getDeviationC()).deviationD(tanswerPojo.getDeviationE())
                .userId(tanswerPojo.getUserId()).build();
        return build;
    }


    // 生成指定范围的随机数字【不重复】
    public  List<Integer> randomNum(int scope, int total) {
        List<Integer> mylist = new ArrayList<>(); // 用于储存不重复的随机数
        Random rd = new Random();
        while (mylist.size() < scope) {
            int myNum = rd.nextInt(total);
            if (!mylist.contains(myNum += 1)) { // 判断容器中是否包含指定的数字
                mylist.add(myNum); // 往集合里面添加数据。
            }
        }
        return mylist;
    }



}
